package top.blackr.folivora.common.notification.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import com.sun.mail.util.MailSSLSocketFactory;
import org.springframework.stereotype.Service;
import top.blackr.folivora.common.notification.NotificationConfig;
import top.blackr.folivora.common.notification.NotificationProperties;
import top.blackr.folivora.common.notification.NotificationService;

import java.security.GeneralSecurityException;

/**
 * @author BlackR
 */
@Service("email")
public record Email(NotificationProperties.Email properties) implements NotificationService {

    private static MailAccount mailAccount;

    @Override
    public String send(NotificationConfig config) {
        mailAccount = getMailAccount();
        config.getTargets().add(config.getTarget());
        return MailUtil.send(mailAccount, config.getTargets(), config.getTitle(), config.getContent(), false);
    }

    private MailAccount getMailAccount() {
        if (ObjectUtil.isEmpty(mailAccount)) {
            mailAccount = new MailAccount();
            // 邮件服务器的SMTP地址
            mailAccount.setHost(properties.getHost());
            // 邮件服务器的SMTP端口
            mailAccount.setPort(properties.getPort());
            mailAccount.setAuth(true);
            mailAccount.setFrom(properties.getFrom());
            mailAccount.setUser(properties.getUser());
            mailAccount.setPass(properties.getPass());
            mailAccount.setSslEnable(true);
            mailAccount.setSocketFactoryClass("javax.net.ssl.SSLSocketFactory");
            mailAccount.setSocketFactoryFallback(true);
            mailAccount.setSocketFactoryPort(465);
            /*
                针对QQ邮箱错误 Could not connect to SMTP host: smtp.qq.com, port: 465
                这个错误可能是需要SSL验证造成的，跳过这个验证
             */
            MailSSLSocketFactory sf;
            try {
                sf = new MailSSLSocketFactory();
            } catch (GeneralSecurityException e) {
                throw new RuntimeException(e);
            }
            sf.setTrustAllHosts(true);
            mailAccount.setCustomProperty("mail.smtp.ssl.socketFactory", sf);
        }
        return mailAccount;
    }
}
